package com.example.administrator.music;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.SeekBar;

public class MainActivity extends AppCompatActivity {
    private MusicConnection conn;
    private boolean isExit=false;
    private Handler handler;
    private SeekBar seekBar;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(conn);

    }

    @Override
    protected void onPause() {
        super.onPause();
        isExit=true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        seekBar=(SeekBar)findViewById(R.id.progress);
        handler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                int progress=msg.getData().getInt("progress");
                int duration=msg.getData().getInt("duration");
                seekBar.setMax(duration);
                seekBar.setProgress(progress);
            }
        };
        conn=new MusicConnection();
        Intent intent=new Intent();
        intent.setClass(this,MusicService.class);
        bindService(intent,conn,BIND_AUTO_CREATE);
        conn.getProgressor();
        new Thread(){
            @Override
            public void run() {
                while(!isExit){
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Progressor pro=conn.getProgressor();
                    if(pro!=null){
                        int progress=pro.getProgress();
                        int duration=pro.getDuration();
                        Log.i("jgh","progress"+progress);
                        Log.i("jgh","duration"+duration);
                        Bundle bundle=new Bundle();
                        bundle.putInt("progress",progress);
                        bundle.putInt("duration",duration);
                        Message msg=new Message();
                        msg.setData(bundle);
                        handler.sendMessage(msg);


                    }
                }
            }
        }.start();

    }
    public void play(View view){

        musicController("play");
    }
    public void pause(View view){

        musicController("pause");
    }
    private void musicController(String action){
        Intent intent=new Intent();
        intent.setClass(this,MusicService.class);
        intent.putExtra("action",action);
        startService(intent);
    }
}
